﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace csexplorer.Util
{
    internal static class DataTableConverter
    {
        public static DataTable GetDataTableFromObjects<TDataClass>(List<TDataClass> dataList)
            where TDataClass : class
        {
            Type t = typeof(TDataClass);
            DataTable dt = new DataTable(t.Name);

            foreach (PropertyInfo pi in t.GetProperties())
            {
                dt.Columns.Add(new DataColumn(pi.Name));
            }

            if (dataList != null)
            {
                foreach (TDataClass item in dataList)
                {
                    DataRow dr = dt.NewRow();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        dr[dc.ColumnName] =
                          item.GetType().GetProperty(dc.ColumnName).GetValue(item, null);
                    }

                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
    }
}
